package com.kob.backend.service.impl.user.account;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kob.backend.mapper.UserMapper;
import com.kob.backend.pojo.User;
import com.kob.backend.service.user.account.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private UserMapper userMapper;//先把userMapper注入进来

    @Autowired
    private PasswordEncoder passwordEncoder;//加密密码

    @Override
    public Map<String, String> register(String username, String password, String confirmedPassword) {
        Map<String,String> map=new HashMap<>();//定义返回结果
        if(username==null){
            map.put("error_message","用户名不能为空");
            return map;
        }
        if(password==null||confirmedPassword==null){
            map.put("error_message","密码不能为空");
            return map;
        }
        username=username.trim();//删掉首尾空白字符
        if(username.length()==0){
            map.put("error_message","用户名不能为空");
            return map;
        }

        if(password.length()==0||confirmedPassword.length()==0){
            map.put("error_message","密码长度不能为0");
            return map;
        }

        if(username.length()>100){
            map.put("error_message","用户名长度不能大于100");
            return map;
        }

        if(password.length()>100||confirmedPassword.length()>100){
            map.put("error_message","密码长度不能大于100");
            return map;
        }

        if(!password.equals(confirmedPassword)){
            map.put("error_message","两次输入的密码不一样");
            return map;
        }

        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        List<User> users=userMapper.selectList(queryWrapper);
        if(!users.isEmpty()){
            map.put("error_message","用户名已存在");
            return map;
        }

        //把用户存到数据库里面
        String encodedPassword=passwordEncoder.encode(password);//加密密码
        String photo="https://cdn.acwing.com/media/user/profile/photo/243803_lg_3e8b34305e.jpg";
        User user=new User(null,username,encodedPassword,photo,1500);//设置插入元组信息
        userMapper.insert(user);//加到数据库内

        map.put("error_message","success");//map应该是存信息的
        return map;
    }
}
